var toPage;
$(function () {
    loadDeviceList();
    loadCompanyList();
    formValidation();
});

const title = ['#', '设备编号', '设备名称', '设备类型', '添加时间', '归属企业', '采集设备是否绑定', '采集设备编号', '维保周期', '操作'];
const label = ['order', 'sn', 'name', 'deviceType', 'createTime', 'ename', 'isBind', 'ceqNumber', 'maintenanceCycle', 'opera'];

function formValidation() {
    $('#addInfoForm').bootstrapValidator({
        feedbackIcons: {
            valid: 'fa fa-check',
            validating: 'fa fa-sync-alt'
        },
        fields: {
            name: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 16,
                    },
                    regexp: {
                        regexp: /^[\u4E00-\u9FA5a-zA-Z0-9_-]+$/,
                        message: '设备名称只能由汉字、字母、数字、横线和下划线组成'
                    }
                }
            },
            sn: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 2,
                        max: 255
                    },
                    regexp: {
                        regexp: /^[a-zA-Z0-9_]+$/,
                        message: '设备编号只能由字母、数字和下划线组成'
                    },
                    threshold: 2, //设置4字符以上开始请求服务器
                    //有待验证，备注以备下次使用。
                    //bootstrap的remote验证器需要的返回结果一定是json格式的数据 :
                    //{"valid":false} //表示不合法，验证不通过
                    //{"valid":true} //表示合法，验证通过
                    remote: {//发起Ajax请求。
                        url: '../device/verificationDeviceByNumber2',//验证地址
                        data: {
                            'methodType': $('input[name="methodType"]').val(),
                            'sn': $('input[name="sn"]').val(),
                            'type': 1,
                            'id': $('input[name="id"]').val()
                        },
                        message: '设备编号以存在',//提示消息
                        delay: 1000,//设置2秒发起验证
                        type: 'POST' //请求方式
                    },
                }
            },
            enterpise: {
                validators: {
                    notEmpty: {
                        message: '请选择归属企业'
                    },
                }
            }, typeOne: {
                validators: {
                    notEmpty: {
                        message: '请选择设备类型'
                    },
                }
            }, group: {
                validators: {
                    threshold: 1, //设置4字符以上开始请求服务器
                    //有待验证，备注以备下次使用。
                    //bootstrap的remote验证器需要的返回结果一定是json格式的数据 :
                    //{"valid":false} //表示不合法，验证不通过
                    //{"valid":true} //表示合法，验证通过
                    remote: {//发起Ajax请求。
                        url: '../device/uniqueCollectionEquipment',//验证地址
                        data: {
                            'group': $('input[name="group"]').val(),
                            'methodType': $('input[name="methodType"]').val(),
                            'id': $('input[name="id"]').val()
                        },
                        message: '采集设备已经被绑定',//提示消息
                        delay: 1000,//设置2秒发起验证
                        type: 'POST' //请求方式
                    }
                }
            }, maintenanceCycle: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^[0-9]+$/,
                        message: '维保周期只能由数字组成'
                    },
                }
            }, maxPrice: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: '峰值电价只能是最多带四位小数的数字'
                    },
                }
            }, position: {
                validators: {
                    notEmpty: {},
                    regexp: {
                        regexp: /^((\-?|\+?)?\d+(\.\d+)?),\s*((\-?|\+?)?\d+(\.\d+)?)$/,
                        message: '请输入正确坐标'
                    },
                }
            }, avgPrice: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: '平值电价只能是最多带四位小数的数字'
                    },
                }
            }, minPrice: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: '谷值电价只能是最多带四位小数的数字'
                    },
                }
            }, maxU: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: '电压峰值只能由数字组成'
                    },
                }
            }, maxI: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: '电流峰值只能由数字组成'
                    },
                }
            }, maxC: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: '电量峰值只能由数字组成'
                    },
                }
            }, standardU: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: '电压标准值只能由数字组成'
                    },
                }
            }, standardI: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: '电流标准值只能由数字组成'
                    },
                }
            }, standardC: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: '电量标准值只能由数字组成'
                    },
                }
            }, standardPower: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: ' 额定功率'
                    },
                }
            }, photoFile: {
                validators: {
                    notEmpty: {
                        message: '上传图片不能为空'
                    },
                    photoFile: {
                        extension: 'png,jpg,jpeg',
                        type: 'image/png,image/jpg,image/jpeg',
                        message: '请重新选择图片'
                    }
                }
            }, IAH: {
                validators: {
                    notEmpty: {},
                    stringLength: {
                        min: 1,
                        max: 10
                    },
                    regexp: {
                        regexp: /^([0-9][0-9]*)+(.[0-9]{1,4})?$/,
                        message: '待机功耗只能是最多带四位小数的数字'
                    },
                }
            }, currentRatio: {
                validators: {
                    notEmpty: {},
                    integer: {}
                }
            }
        }
    }).on('success.form.bv', function (e) {
        //防止表单提交
        e.preventDefault();
        //获取表单实例
        var $form = $(e.target);
        showLoading("正在上传中");
        //获取BootstrapValidator实例
        jQuery.support.cors = true;
        var bv = $form.data('bootstrapValidator');
        var formdata = new FormData($("#addInfoForm")[0]);
        compressPicture($('#add_file_hide').prop('files')[0], 100, 100, 0.75, function (blob) {
            if (!isNull(blob)) {
                formdata.append('thumbnail', blob);
            }
            ////使用Ajax提交表单数据
            $.ajax({
                url: "../device/saveProductionEquipment",
                type: 'POST',
                data: formdata,
                datatype: 'json',
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function (xhr) {
                    xhr.setRequestHeader('token', sessionStorage.getItem("token"));
                },
                success: function (data) {
                    hideLoading();
                    if (data.status == 200) {
                        myAlert("提示", "保存成功", function () {
                            loadPrdEquManagementList(toPage);
                            $('#addInfoModal').modal('hide');
                            return;
                        })
                    } else {
                        myAlert("提示", "保存失败", function () {
                            return;
                        })
                    }
                    myAlert("提示", data.msg, function () {
                        $('[type="submit"]').removeAttr("disabled");
                    })
                },
                error: function (data) {
                    myAlert("提示", data.msg, function () {
                        $('[type="submit"]').removeAttr("disabled");
                    })
                }
            })
        });
    }).on('error.form.bv', function (e) { //点击提交验证失败之后
        $('[type="submit"]').removeAttr("disabled");
    });
}

/*加载企业信息下拉框*/
function loadCompanyList() {
    getJson("/enterprise/findEnterpriseS", null, 'GET', function (res) {
        if (res.code == 200) {
            var resData = res.payload.data;
            resData.map(function (item, index) {
                item.text = item.name;
            });
            $('#company-list').selectivity({
                items: resData,
                placeholder: '选择企业'
            });
            $('#search_company').selectivity({
                items: resData,
                placeholder: '选择归属企业'
            });
        } else {
            myAlert("提示", res.message);
        }
    })

}

/**
 * 加载生产设备信息
 */
function loadDeviceList(_pageIndex) {
    $('#addInfoModal').modal('hide');
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage = pageIndex;
    showLoading(LOADING);
    let param = $("#param-id").val();
    getJson("/device/getProductionEquipment", {
            param: param
            , pageIndex: pageIndex,
            pageSize: 10
        },
        'GET',
        function (result) {
            buildData(result,pageIndex);
        })
}


function loadPrdEquManagementList(_pageIndex) {
    $('#addInfoModal').modal('hide');
    let pageIndex = parseInt(_pageIndex ? _pageIndex : '1');
    toPage = pageIndex;
    showLoading(LOADING);
    let param = $("#param-id").val();
    let company = $("#search_company").selectivity('val');
    getJson("/device/getProductionEquipment", {
            enterprise:company,
            bind:$('#bind').val(),
            param: param,
            pageIndex: pageIndex,
            pageSize: 10
        },
        'GET',
        function (result) {
            buildData(result,pageIndex);
        })
}

function buildData(result,pageIndex) {
    if (result['code'] == 200) {
        let data = result['payload']['data'];
        setPage($('#page'), pageIndex, result['payload']['pages'], result['payload']['total'], function (num) {
            loadPrdEquManagementList(num);
        });
        let order = 1 + 10 * (pageIndex - 1);
        for (let item of data) {
            item['order'] = order++;
        }
        for (let item of data) {
            item['createTime'] = getDate(item['createTime']).datetime();
        }
        buildTable($('#PEM-List'), title, label, data, function (td, label, item) {
            switch (label) {
                case 'maintenanceCycle':
                    $(td).text(item[label] + '天');
                    break;
                case 'deviceType':
                    $(td).text(item['typeThreeName'] || item['typeTowName'] || item['typeOneName']);
                    break;
                case 'isBind':
                    let span = createElement('span', td, null, null);
                    $(span).addClass("badge font-p14");
                    if (isNull(item['ceqNumber'])) {
                        $(span).addClass("badge-danger");
                        $(span).text("未绑定");
                    } else {
                        $(span).addClass("badge-primary");
                        $(span).text("已绑定");
                    }
                    break;
                case 'opera':
                    let opera = createElement('div', td, null, null);
                    $(opera).addClass('dropdown');
                    let a_opera = createElement('a', opera, '操作', null);
                    $(a_opera).addClass('dropdown-toggle');
                    $(a_opera).attr('data-toggle', 'dropdown');
                    $(a_opera).attr('href', '#');
                    let div_opera = createElement('div', opera, null, null);
                    $(div_opera).addClass('dropdown-menu');
                    $(div_opera).addClass('dropdown-menu-right');
                    if (whetherPermissionViewing) {
                        let info = createElement('a', div_opera, '详情', null);
                        $(info).addClass('dropdown-item');
                        $(info).click(function () {
                            viewMore(item['id']);
                        });
                    }
                    if (whetherPermissionModify) {
                        let modify = createElement('a', div_opera, '修改', null);
                        $(modify).addClass('dropdown-item');
                        $(modify).click(function () {
                            editInfo(item['id']);
                        });
                        let cody = createElement('a', div_opera, '复制', null);
                        $(cody).addClass('dropdown-item');
                        $(cody).click(function () {
                            copyInfo(item['id']);
                        });
                        if (isNull(item['ceqNumber'])) {
                            let delDev = createElement('a', div_opera, '删除', null);
                            $(delDev).addClass('dropdown-item');
                            $(delDev).click(function () {
                                deleteInfo(item['id']);
                            });
                        } else {
                            let delDev = createElement('a', div_opera, '解绑', null);
                            $(delDev).addClass('dropdown-item');
                            $(delDev).click(function () {
                                untie(item['id']);
                            });
                        }

                    }
                    break;
            }
        });
        hideLoading();
    } else {
        myAlert("提示", result['message']);
    }
}

function check(e) {
    let iah = $('#validationCustom22').val();
    let group = $('#validationCustom04').val();
    if (isNull(group)) {
        myAlert("提示", "请选择采集设备！")
        return;
    }
    if (e == 1) {
        if (isNull(iah)) {
            myAlert("提示", "请先填写待机能耗！")
            return;
        }
    }
    $('#device_status').empty();
    showLoading(LOADING);
    getJson("/device/checkThreshold", {group: group, type: e, value: iah}, "GET", function (result) {
        hideLoading();
        if (result['code'] == 200) {
            myAlert("提示", "校准命令发送成功", function () {
                if (e == 2) {
                    if (isNull(result['payload']['data'])) {
                        myAlert("提示", "获取校验值失败");
                        return;
                    }
                    $('#validationCustom22').val(Number(Number(result['payload']['data']).toFixed(4)));
                }
            });
        } else {
            myAlert("提示", "校准命令发送失败");
        }
    })
}

function untie(id) {
    myConfirm("提示", "设备解绑后无法提供能耗数据，历史数据保留，您是否要解绑此设备", function (res) {
        if (res) {
            getJson("/device/unbindDevice", {id: id}, 'POST', function (result) {
                if (result['code'] == 200) {
                    myAlert("提示", "解绑成功");
                    loadPrdEquManagementList(toPage);
                } else {
                    myAlert("提示", "解绑失败");
                }
            })
        }
    })
}

/*添加*/
function addInfo() {
    $('#device_status').empty();
    loadDeviceType();
    $('#device_type').empty();
    $('#addInfoForm')[0].reset();//清空表单
    $('#company-list').selectivity('val', '');
    $('#type-id').val(0);
    $('#img_load_area').attr('src', '../customize/images/icon/image-upload.png');
    $('#modal_title').text('添加生产设备');
    $('#addInfoModal').modal();
    $("#addInfoForm").data('bootstrapValidator').destroy();
    $('#addInfoForm').data('bootstrapValidator', null);
    $("#validationCustom04").empty();
    $("#device-type").empty();
    $("#device-type-child").empty();
    $("#device-type-child-child").empty();
    $(new Option('请选择', '')).appendTo($("#validationCustom04"));
    $(new Option('请选择', '')).appendTo($("#device-type"));
    $(new Option('无', '')).appendTo($("#device-type-child"));
    $(new Option('无', '')).appendTo($("#device-type-child-child"));
    formValidation();
}

/*查看详情*/
function viewMore(e) {
    /*根据ID查询信息*/
    getJson("/device/getProduceDeviceById", {"id": e}, 'GET', function (result) {
        if (result.status == 200) {
            let data = result.data;
            $('#name-id').text(data.name);
            $('#sn-id').text(data.sn);
            $('#ename-id').text(data.ename);
            $('#ceqNumber-id').text(data.ceqNumber);
            $('#port-id').text(data.port);
            $('#maintenanceCycle-id').text(data.maintenanceCycle + "天");
            $('#minPrice-id').text(data.minPrice + '元/kWh');
            $('#maxPrice-id').text(data.maxPrice + '元/kWh');
            $('#avgPrice-id').text(data.avgPrice + '元/kWh');
            $('#maxU-id').text(data.maxU + 'V');
            $('#maxI-id').text(data.maxI + 'A');
            $('#maxC-id').text(data.maxC + 'kWh');
            $('#standardU-id').text(data.standardU + 'V');
            $('#standardI-id').text(data.standardI + 'A');
            $('#standardC-id').text(data.standardC + 'kWh');
            $('#standardPower-id').text(data.standardPower + "kW");
            $('#createTime-id').text(getDate(data.createTime).datetime());
            $('#qddl').text(data.iah + 'kW');
            // $('#djdl').text(data.ial + 'A');
            $('#dlb').text(data.currentRatio);
            let deviceType = '';
            if (data['typeOneName']) {
                deviceType += data['typeOneName'];
                if (data['typeTowName']) {
                    deviceType += '/' + data['typeTowName'];
                    if (data['typeThreeName']) {
                        deviceType += '/' + data['typeThreeName'];
                    }
                }
            }
            $('#deviceType').text(deviceType);
            if (!isNull(data.image)) {
                $('#logo-id').attr('src', fileUrl + data.image);
                $('#logo-id')[0].onerror = function () {//加载出错时，替换为默认图
                    $(this).attr('src', '../customize/images/device-img.png');
                }
            } else {//无图片加载默认图
                $('#logo-id').attr('src', '../customize/images/device-img.png');
            }
        } else {
            myAlert("提示", "加载设备数据失败");
        }
    })
    $('#viewInfoModal').modal();
}

/*修改信息*/
function editInfo(e) {
    $('#device_status').empty();
    $('#addInfoForm')[0].reset();//清空表单
    $('#company-list').selectivity('val', '');
    $('#type-id').val(1);
    /*根据ID查询信息*/
    getJson("/device/getProduceDeviceById", {"id": e}, 'GET', function (result) {
        if (result.status == 200) {
            let data = result.data;
            loadGroup(data.enterpise, data.group);
            $('#validationCustom01').val(data.name);
            $('#validationCustom02').val(data.sn);
            $('#company-list-vld').val(data.enterpise);
            $('#company-list').selectivity('val', data.enterpise);
            $('#device_type').val(data.deviceType);
            $('#position_id').val(data.position);
            $('#validationCustom05').val(data.port);
            $('#validationCustom06').val(data.maintenanceCycle);
            $('#validationCustom07').val(data.maxPrice);
            $('#validationCustom08').val(data.avgPrice);
            $('#validationCustom09').val(data.minPrice);
            $('#validationCustom11').val(data.maxU);
            $('#validationCustom12').val(data.maxI);
            $('#validationCustom13').val(data.maxC);
            $('#validationCustom14').val(data.standardU);
            $('#validationCustom15').val(data.standardI);
            $('#validationCustom16').val(data.standardC);
            $('#validationCustom21').val(data.standardPower);
            $('#validationCustom22').val(data.iah);
            // $('#validationCustom23').val(data.ial);
            $('#validationCustom24').val(data.currentRatio);
            if (!isNull(data.image)) {
                $('#img_load_area').attr('src', fileUrl + data.image);
            }
            if (!isNull(data['typeOne'])) {
                getDeviceType($('#device-type'), data['typeOne'], $('#device-type-child'), data['typeTow'], $('#device-type-child-child'), data['typeThree']);
            } else {
                loadDeviceType();
            }
        } else {
            myAlert("提示", "加载设备数据失败");
        }
    })
    $('#type-id').val(1);
    $('#d-id').val(e);
    $('#modal_title').text('修改生产设备信息');
    $('#addInfoModal').modal();
    $("#addInfoForm").data('bootstrapValidator').destroy();
    $('#addInfoForm').data('bootstrapValidator', null);
    formValidation();
}

/*复制*/
function copyInfo(e) {
    $('#device_status').empty();
    loadDeviceType();
    $('#type-id').val(0);
    $('#addInfoForm')[0].reset();//清空表单
    $('#company-list').selectivity('val', '');
    /*重写加载表单验证*/
    $("#addInfoForm").data('bootstrapValidator').destroy();
    $('#addInfoForm').data('bootstrapValidator', null);
    formValidation();
    $('#img_load_area').attr('src', '../customize/images/icon/image-upload.png');
    //复制，即为复制当前设备的配置信息为下一台设备的配置；名称、编号不可复用
    /*根据ID查询信息*/
    getJson("/device/getProduceDeviceById", {"id": e}, 'GET', function (result) {
        if (result.status == 200) {
            let data = result.data;
            loadGroupTwo(data.enterpise, data.group);
            $('#company-list-vld').val(data.enterpise);
            $('#company-list').selectivity('val', data.enterpise);
            $('#validationCustom04').val(data.group);
            $('#validationCustom05').val(data.port);
            $('#validationCustom06').val(data.maintenanceCycle);
            $('#validationCustom07').val(data.maxPrice);
            $('#validationCustom08').val(data.avgPrice);
            $('#validationCustom09').val(data.minPrice);
            $('#validationCustom11').val(data.maxU);
            $('#validationCustom12').val(data.maxI);
            $('#validationCustom13').val(data.maxC);
            $('#validationCustom14').val(data.standardU);
            $('#validationCustom15').val(data.standardI);
            $('#validationCustom16').val(data.standardC);
            $('#validationCustom21').val(data.standardPower);
            $('#validationCustom22').val(data.iah);
            // $('#validationCustom23').val(data.ial);
            getDeviceType($('#device-type'), data['typeOne'], $('#device-type-child'), data['typeTow'], $('#device-type-child-child'), data['typeThree']);
        } else {
            myAlert("提示", "加载设备数据失败");
        }
    })
    $('#modal_title').text('复制生产设备信息');
    $('#addInfoModal').modal();
}


function deleteInfo(e) {
    myConfirm("提示", "设备删除后用电数据将丢失，您是否要删除此设备信息", function (res) {
        if (res) {
            getJson("/device/deleteDevice", {"id": e}, 'GET', function (result) {
                if (result.code == '200') {
                    myAlert("提示", "删除成功", function () {
                        loadPrdEquManagementList(toPage);
                        $('#addInfoModal').modal('hide');
                    })
                } else {
                    myAlert("提示", result.message)
                }
            })
        }
    })
}

/*选择的图片加载到预览区*/
$('#add_file_hide').change(function (e) {
    if (this.files[0].size / 1024 / 1024 > 10) {
        myAlert("提示", "选择的图片不能超过10M");
        return;
    }
    var _URL = window.URL || window.webkitURL;
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function () {
            $('#img_load_area').attr('src', this.src);
        };
        img.src = _URL.createObjectURL(file);
    }
})

function loadGroup(e, val) {
    if (e) {
        getJson("/device/getDevicesByCompany", {"company": e, "id": val}, 'GET', function (result) {
            $("#validationCustom04").empty();
            $(new Option('', '')).appendTo($("#validationCustom04"));
            for (let i = 0; i < result.length; i++) {
                $(new Option(result[i].name, result[i].id)).appendTo($("#validationCustom04"));
                if (val) {
                    $('#validationCustom04').val(val);
                }
            }
        })
    } else {
        $("#validationCustom04").empty();
        $(new Option('请选择', '')).appendTo($("#validationCustom04"));
    }
}

function loadGroupTwo(e, val) {
    $('#company-list-vld').val(e);
    if ($('#type-id').val() == 1) {
        return;
    }
    $('#addInfoForm').data('bootstrapValidator').updateStatus('enterpise', 'NOT_VALIDATED', null).validateField('enterpise');//重置并触发字段的验证
    if (e) {
        getJson("/device/getDevicesByCompanyTwo", {"company": e}, 'GET', function (result) {
            $("#validationCustom04").empty();
            $(new Option('', '')).appendTo($("#validationCustom04"));
            if (val && val.group != null && val.group != 0) {
                $(new Option(val.sn, val.group)).appendTo($("#validationCustom04"));
            }
            for (let i = 0; i < result.length; i++) {
                $(new Option(result[i].name, result[i].id)).appendTo($("#validationCustom04"));
            }
            if (val && val.group) {
                $('#validationCustom04').val(val.group);
            }
        })
    } else {
        $("#validationCustom04").empty();
        $(new Option('请选择', '')).appendTo($("#validationCustom04"));
    }
}

function loadDeviceType(e, child) {
    getJson("/deviceType/selectAllByParentId", {parentId: $(e).val()}, 'GET', function (result) {
        if (isNull(child)) {
            buildSelectNoData($('#device-type'), result['payload']['data'], 'title', 'id', '请选择');
        } else {
            buildSelectNoData($(child), result['payload']['data'], 'title', 'id', '无');
        }
    })
    selectData();
}

function selectData() {
    let type1 = $('#device-type').val() == '无' ? undefined : $('#device-type').val();
    let type2 = $('#device-type-child').val() == '无' ? undefined : $('#device-type-child').val();
    let type3 = $('#device-type-child-child').val() == '无' ? undefined : $('#device-type-child-child').val();
    $('#device_type').val(type3 || type2 || type1);
}

/**
 * 获取设备类型方法
 * @param eTypeOne 设备类型1（select元素）
 * @param typeOne 选中设备类型1（ID）（可选）
 * @param eTypeTwo 设备类型2 （select元素）（可选 如果填city的话必选）
 * @param typeTwo 选中设备类型2（ID）（可选）
 * @param eTypeThree 设备类型3 （select元素）（可选 如果填city的话必选）
 * @param typeThree 选中设备类型3（ID）（可选）
 */
function getDeviceType(eTypeOne, typeOne, eTypeTwo, typeTwo, eTypeThree, typeThree) {
    getJson("/deviceType/selectAllByParentId", {parentId: 0}, 'GET', function (result) {
        if (!isNull(result['payload']['data'])) {
            buildSelectNoData(eTypeOne, result['payload']['data'], 'title', 'id', '请选择', typeOne);
            getJson("/deviceType/selectAllByParentId", {parentId: typeOne}, 'GET', function (result) {
                if (!isNull(result['payload']['data'])) {
                    buildSelectNoData(eTypeTwo, result['payload']['data'], 'title', 'id', '无', typeTwo);
                    getJson("/deviceType/selectAllByParentId", {parentId: typeTwo}, 'GET', function (result) {
                        if (!isNull(result['payload']['data'])) {
                            buildSelectNoData(eTypeThree, result['payload']['data'], 'title', 'id', '无', typeThree);
                        }
                    })
                }
            })
        }
    })
}
